<template>
  <div class="secondary-auth-page">
    <el-result icon="warning" :title="''">
      <template #title>
        <div class="custom-title">需要二次认证</div>
        <div class="sub-title">请使用微信扫描下方二维码完成身份验证</div>
      </template>
      <template #extra>
        <div class="qr-container">
          <iframe
            :src="qrCodeUrl"
            frameborder="0"
            scrolling="no"
            class="qr-iframe"
            name="oauth-iframe"
          />
        </div>
      </template>
    </el-result>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElResult } from "element-plus";
import { removeAuthLimit } from "@/api";

const qrCodeUrl = ref("");

// 获取二维码
const getQRCode = () => {
  try {
    const APPID = "ndd956a392c8b55d39";
    // 将回调地址指向当前页面
    const currentUrl = encodeURIComponent(window.location.href);
    qrCodeUrl.value = `https://oauth.henau.edu.cn/oauth2_qr_connect/login?appid=${APPID}&redirect_uri=${currentUrl}&response_type=code&scope=henauapi_login&target=oauth-iframe&hidetips=true`;
  } catch (error) {
    console.error("获取二维码失败:", error);
  }
};

// 处理认证成功
const handleAuthSuccess = async (code: string) => {
  try {
    // 调用解除限制接口
    const res = await removeAuthLimit(code);
    if (res.status === "success") {
      ElMessage.success(res.msg || "解除限制成功！");
      // 向父窗口发送成功消息
      window.opener?.postMessage(
        {
          type: "auth-success",
          code,
          msg: res.msg || "解除限制成功！"
        },
        window.location.origin
      );
      // 延迟关闭窗口
      setTimeout(() => {
        window.close();
      }, 1000);
    } else {
      ElMessage.error(res.msg || "认证失败");
    }
  } catch (error) {
    console.error("解除限制失败:", error);
    ElMessage.error("认证失败");
  }
};

// 检查URL中的code参数
const checkUrlCode = () => {
  try {
    // 获取完整的hash部分（包括查询参数）
    const fullHash = window.location.hash;
    // 使用正则表达式匹配code参数
    const codeMatch = fullHash.match(/code=([^&]+)/);
    if (codeMatch && codeMatch[1]) {
      const code = codeMatch[1];
      handleAuthSuccess(code);
    }
  } catch (error) {
    console.error("处理code参数失败:", error);
  }
};

// 处理OAuth回调消息
const handleOAuthMessage = (event: MessageEvent) => {
  try {
    // 验证消息来源
    if (event.origin !== "https://oauth.henau.edu.cn") return;

    const data = event.data;
    // 处理iframe内部的认证成功消息
    if (data.type === "oauth_success" && data.code) {
      handleAuthSuccess(data.code);
      return;
    }

    // 处理重定向回来的认证成功消息
    if (typeof data === "string") {
      // 处理特殊格式的URL: /user/index?target=oauth-iframe?code=xxx
      const codeMatch = data.match(/code=([^&]+)/);
      if (codeMatch && codeMatch[1]) {
        handleAuthSuccess(codeMatch[1]);
      }
    }
  } catch (error) {
    console.error("处理OAuth消息失败:", error);
  }
};

onMounted(() => {
  getQRCode();
  // 检查URL中的code参数
  checkUrlCode();
  // 添加消息监听
  window.addEventListener("message", handleOAuthMessage);
});
</script>

<style lang="scss" scoped>
.secondary-auth-page {
  display: flex;
  justify-content: center;
  min-height: 80vh;
  padding-top: 0;

  :deep(.el-result) {
    padding: 24px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  }

  :deep(.el-result__icon) {
    position: relative;
    top: 20px;
  }

  :deep(.el-result__title) {
    position: relative;
    top: 20px;
    margin-top: 0;
    margin-bottom: 8px;
    font-size: 20px;
    color: #000;
  }

  :deep(.el-result__subtitle) {
    margin-top: -100px;
    margin-bottom: -50px;
    font-size: 14px;
  }

  .qr-container {
    position: relative;
    top: -10px;
    width: 320px;
    height: 300px;
    margin: 0 auto;
    overflow: hidden;

    .qr-iframe {
      width: 100%;
      height: 100%;
      transform: scale(1.15);
      transform-origin: center center;
    }
  }

  .custom-title {
    position: relative;
    top: 10px;
    margin-top: 0;
    margin-bottom: 8px;
    font-size: 20px;
    font-weight: bold;
    color: #000;
  }

  .sub-title {
    margin-top: 8px;
    font-size: 14px;
    color: #666;
  }
}
</style>
